package ioc

import (
	"JK-Junior-Go-Engineer-Camp/webook/internal/repository/dao"
	"JK-Junior-Go-Engineer-Camp/webook/pkg/logger"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	glogger "gorm.io/gorm/logger"
)

// InitDB 初始化数据库
func InitDB(l logger.LoggerV1) *gorm.DB {
	type Config struct {
		DSN string `yaml:"dsn"`
	}
	cfg := Config{DSN: "root:root@tcp(localhost:13316)/webook"}
	err := viper.UnmarshalKey("db", &cfg)
	if err != nil {
		panic(err)
	}

	db, err := gorm.Open(mysql.Open(cfg.DSN), &gorm.Config{
		Logger: glogger.New(gormLoggerFunc(l.Debug), glogger.Config{
			SlowThreshold: 0, // 慢查询阈值
			LogLevel:      glogger.Info,
		}),
	})
	if err != nil {
		panic(err)
	}
	db = db.Debug()
	err = dao.InitTables(db)
	if err != nil {
		panic(err)
	}
	return db
}

// gormLoggerFunc 实现了 glogger.Writer 接口
// func(msg string, fields ...logger.Field) 函数类型的衍生类型
type gormLoggerFunc func(msg string, fields ...logger.Field)

func (g gormLoggerFunc) Printf(msg string, fields ...interface{}) {
	g(msg, logger.Field{Key: "fields", Val: fields})
}
